package com.atguigu.gulimall.seckill.scheduled;

import com.atguigu.gulimall.seckill.service.SeckillService;
import com.sun.xml.internal.bind.v2.TODO;
import com.sun.xml.internal.ws.developer.Serialization;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SeckillSkuScheduled {

    @Autowired
    private RedissonClient redissonClient;

    private final String UPLOAD_LOCK = "seckill:upload:lock";

    @Autowired
    private SeckillService seckillService;

    /**
     * 上架秒杀商品
     */
    // todo 幂等性（防止商品重复上架）
    @Scheduled(cron = "0/10 * * * * ?")
    public void uploadSeckillSkuLatest3Days() {
        log.info("上架秒杀商品。。。");

        /*
        分布式集群下，定时任务到时间后都开始启动，会导致商品重复上架
        需要使用分布式锁处理，让一个节点先上架，后续节点如果上架，也会有幂等性保证商品只上架一次
         */
        RLock lock = redissonClient.getLock(UPLOAD_LOCK);
        lock.lock(10, TimeUnit.SECONDS);

        try {
            seckillService.uploadSeckillSkuLatest3Days();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


}
